/**
 *
 */
package com.zzw.utils;

import jakarta.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;

import java.util.Objects;
import java.util.stream.Stream;

/**
 * @author liuyulong
 */
public class IpUtils {

    private static final String[] IP_HEADERS = new String[]{"x-forwarded-for", "x-real-ip", "proxy_protocol_addr",
            "remote-host", "Proxy-Client-IP", "WL-Proxy-Client-IP"};

    private static String getValue(String value) {
        if (StringUtils.isBlank(value) || "unknown".equalsIgnoreCase(value)) {
            return null;
        }
        return value;
    }

    public static String tryGetRealIp(HttpServletRequest request) {
        String headerValue = Stream.of(IP_HEADERS)
                .map(header -> {
                    String value = getValue(request.getHeader(header));
                    if (null == value) {
                        value = getValue(request.getHeader(header.toUpperCase()));
                    }
                    if (null == value) {
                        value = getValue(request.getHeader(header.toLowerCase()));
                    }
                    return value;
                })//
                .filter(Objects::nonNull)
                .findFirst()
                .orElse(null);
        String ip;
        if (null != headerValue) {
            if (headerValue.contains(",")) {
                ip = Stream.of(StringUtils.split(headerValue, ","))
                        .filter(StringUtils::isNotBlank)
                        .findFirst()
                        .orElse(null);
            } else {
                ip = headerValue;
            }
        } else {
            ip = request.getRemoteAddr();
        }
        return ip;
    }
}
